<template>
  <div class="app-container">
    <common-table
      :colnames="colnames"
      :list-data="listData"
      :list-loading="listLoading"
      :is-multiple="isMultiSelect"
      @fetchData="fetchData"
      @itemNew="itemNew"
      @itemEdit="itemEdit"
      @itemDelete="itemDelete"
      @changeSwitch="changeSwitch"
    >
      <template v-slot:filter>
        <el-row type="flex">
          <el-input
            v-model="listQuery.stationName"
            placeholder="请输入场站名称"
            clearable
            style="width: 220px"
            size="mini"
          />
          <el-select
            v-model="listQuery.stationStatus"
            placeholder="请选择场站状态"
            style="margin-left: 15px"
            size="mini"
            class="ml15"
            clearable
          >
            <el-option label="已启用" :value="1" />
            <el-option label="已禁用" :value="0" />
          </el-select>
          <el-select
            v-model="listQuery.thirdOpen"
            placeholder="请选择第三方开放状态"
            style="margin-left: 15px"
            size="mini"
            class="ml15"
            clearable
          >
            <el-option label="开放" :value="1" />
            <el-option label="未开放" :value="0" />
          </el-select>
          <el-cascader
            v-model="filter.addrProvince"
            size="mini"
            :options="provinceOptions"
            placeholder="请选择地址"
            style="width: 220px; margin-left: 15px; margin-right: 15px"
            clearable
            @change="addressChange"
          />
          <el-button
            type="primary"
            size="mini"
            class="ml5"
            @click="fetchData(listQuery, true)"
            >查询</el-button
          >
          <el-button size="mini" class="ml5" @click="exportExcelDia(listQuery)"
            >导出</el-button
          >
        </el-row>
      </template>
      <!-- <template v-slot:leftPannel>
        <el-button size="mini" type="default" @click="downloadTemplate()">下载模板</el-button>
        <el-button size="mini" type="primary" @click="importData()">导入数据</el-button>
      </template> -->
    </common-table>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="40%"
      destroy-on-close
    >
      <common-edit
        :fields="editCols"
        :edit-type="editType"
        :values="editValues"
        :rules="editRules"
        @onCancel="dialogVisible = false"
        @onSubmit="onSubmit"
      />
    </el-dialog>

    <el-dialog
      title="导入数据"
      :visible.sync="dialogUploadVisible"
      width="50%"
      destroy-on-close
    >
      <el-upload
        class="upload-demo"
        drag
        :action="`${baseUrl}/v2/station/import`"
        :headers="uploadHeader"
        :on-error="uploadError"
        :on-success="uploadSuccess"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">
          只能上传xlsx文件，且不超过10MB
        </div>
      </el-upload>
      <el-button type="primary" @click="uploadDone"> 确定 </el-button>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import CommonTable from "../commontable";
import CommonEdit from "../commontable/edit";
import { isEmpty } from "@/utils/validate";
import {
  updatePush,
  thirdOpen,
  getStationList,
  addStation,
  putStation,
  delStation,
  exportStation,
  downloadTemplate,
} from "@/api/station";
import { batchDel, mergeQuerrys } from "@/utils";
import {
  provinceAndCityData,
  CodeToText /*, TextToCode */,
} from "element-china-area-data";
import { getToken } from "@/utils/auth";

export default {
  name: "Station",
  components: { CommonTable, CommonEdit },
  data() {
    const validateEmpty = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback(new Error("不能为空"));
      } else {
        callback();
      }
    };
    return {
      colnames: [
        {
          displayName: "序号",
          colName: "id",
          dataType: "indexNo",
          colWidth: "64px",
          sortable: false,
        },
        { displayName: "TRT", colName: "trtNo", sortable: false },
        {
          displayName: "名称",
          colName: "stationName",
          dataType: "route",
          sortable: false,
          route: {
            name: "Detail",
            params: { stationId: "id", stationName: "stationName" },
          },
        },
        {
          displayName: "省市",
          dataType: "combine",
          data: {
            cols: [{ name: "addrProvince" }, { name: "addrCity" }],
          },
          sortable: false,
        },
        { displayName: "位置", colName: "addrDesc", sortable: false },
        {
          displayName: "场站状态",
          colName: "stationStatus",
          sortable: false,
          formater: (v) => {
            return v === 1 ? "已启用" : "已禁用";
          },
        },
        {
          displayName: "工单推送",
          colName: "pushStatus",
          dataType: "switch",
          sortable: "costom",
        },
        {
          displayName: "第三方是否开放",
          colName: "thirdOpen",
          dataType: "switch",
          sortable: "costom",
        },
        {
          displayName: "创建时间",
          colName: "createDate",
          dataType: "date",
          sortable: "costom",
        },
        // { displayName: '管理区域', colName: 'none1', colText: '管理区域', dataType: 'route',
        //   route: { name: 'Section', params: { stationId: 'id', stationName: 'stationName' }}
        // },
        // { displayName: '管理车位', colName: 'none2', colText: '管理车位', dataType: 'route',
        //   route: { name: 'Place', params: { stationId: 'id', stationName: 'stationName' }}
        // },
        {
          displayName: "操作",
          dataType: "oprators",
          data: {
            ops: [
              { name: "编辑", click: "itemUpdate" },
              { name: "删除", click: "itemDelete" },
            ],
          },
        },
      ],
      editCols: [
        { displayName: "ID", colName: "id", disabled: true },
        { displayName: "名称", colName: "stationName" },
        {
          displayName: "场站状态",
          colName: "stationStatus",
          disabled: true,
          dataType: "select",
          data: {
            options: [
              { name: "禁用", value: 0 },
              { name: "启用", value: 1 },
            ],
          },
        },
        { displayName: "特斯拉TRT ID", colName: "trtNo" },
        {
          displayName: "省市",
          colName: "combineProvinceAndCity",
          dataType: "combineProvinceAndCity",
          data: {
            province: { name: "addrProvince" },
            city: { name: "addrCity" },
          },
        },
        {
          displayName: "选择地址",
          colName: "qqMap",
          dataType: "qqMap",
          data: {
            lat: { name: "stationLat" },
            lng: { name: "stationLng" },
            province: { name: "addrProvince" },
            city: { name: "addrCity" },
            address: { name: "addrDesc" },
          },
        },
        // { displayName: '详细地址', colName: 'addrDesc', dataType: 'address', data: {
        //   provinceCol: 'addrProvince', cityCol: 'addrCity', areaCol: 'addrCounty'
        // }},
        { displayName: "详细地址", colName: "addrDesc" },
        { displayName: "经度", colName: "stationLng", dataType: "number" },
        { displayName: "纬度", colName: "stationLat", dataType: "number" },
        {
          displayName: "场站分区",
          colName: "isMultiple",
          dataType: "selectEx",
          disabled: true,
          data: {
            options: [
              { name: "单一", value: 0 },
              { name: "多个", value: 1 },
            ],
            note: {
              // 带提示信息或按钮扩展的, add和edit分别对应新建和编辑模式下的内容
              add: { type: "text", label: "新建场站后可管理分区" },
              edit: {
                type: "button",
                label: "分区管理",
                onclick: (form, item) => {
                  this.$router.push({
                    name: "Section",
                    params: {
                      stationId: form.id,
                      stationName: form.stationName,
                    },
                  });
                },
              },
            },
          },
        },
        // { displayName: '场站分区', colName: 'isMultiple', dataType: 'selectPanel', data: {
        //   options: [
        //     { name: '单一', value: 0 },
        //     { name: '多个', value: 1 }
        //   ]
        // }, subPanels: {
        //   0: [],
        //   1: [
        //     { displayName: '分区数量', colName: 'sectionCount', dataType: 'listInput', data: (count) => {
        //       const arr = []
        //       for (let i = 0; i < count; i++) {
        //         arr.push({ displayName: `分区${i + 1}名称`, colName: `sectionList${i}` })
        //       }
        //       return arr
        //     } }
        //   ]
        // }},
        { displayName: "描述", colName: "stationDesc", dataType: "textarea" },
        // { displayName: '详细地址', colName: 'addrDetailInfo' },
        // { displayName: '省', colName: 'addrProvince', dataType: 'selProvince', data: { code: 'provinceCode' }},
        // { displayName: '市', colName: 'addrCity', dataType: 'selCity', data: { code: 'cityCode' }},
        // { displayName: '区/县', colName: 'addrCounty', dataType: 'selArea' },
        // { displayName: '省编号', colName: 'provinceCode', dataType: 'provinceCode' },
        // { displayName: '市编号', colName: 'cityCode', dataType: 'cityCode' },
        // { displayName: '备注', colName: 'remark' }
      ],
      editType: "edit",
      editValues: {},
      editRules: {
        stationName: [
          { required: true, trigger: "blur", validator: validateEmpty },
        ],
        stationCapacity: [
          { required: true, trigger: "blur", validator: validateEmpty },
          { type: "number", message: "请输入正确的编号" },
        ],
        addrDesc: [
          { required: true, trigger: "blur", validator: validateEmpty },
        ],
        addrDetailInfo: [
          { required: true, trigger: "blur", validator: validateEmpty },
        ],
        addrProvince: [
          { required: true, trigger: "blur", validator: validateEmpty },
        ],
        addrCity: [
          { required: true, trigger: "blur", validator: validateEmpty },
        ],
        addrCounty: [
          { required: true, trigger: "blur", validator: validateEmpty },
        ],
        provinceCode: [
          { required: true, trigger: "blur", message: "不能为空" },
          { type: "number", message: "请输入正确的编号" },
        ],
        cityCode: [
          { required: true, trigger: "blur", message: "不能为空" },
          { type: "number", message: "请输入正确的编号" },
        ],
        trtNo: [{ required: true, trigger: "blur", message: "不能为空" }],
        // stationLng: [{ required: true, trigger: 'blur', message: '不能为空' },
        //   { type: 'number', message: '请输入正确的坐标' }],
        // stationLat: [{ required: true, trigger: 'blur', message: '不能为空' },
        //   { type: 'number', message: '请输入正确的坐标' }]
        // stationDesc: [{ required: false, trigger: 'blur', validator: validateEmpty }]
      },
      listData: {},
      listLoading: false,
      isMultiSelect: true,
      dialogVisible: false,
      dialogUploadVisible: false,
      dialogTitle: "新建",
      listQuery: {},
      provinceOptions: provinceAndCityData,
      filter: {
        addrProvince: [],
      },
    };
  },
  computed: {
    ...mapGetters(["user", "name", "avatar", "roles"]),
    baseUrl() {
      return process.env.VUE_APP_BASE_API;
    },
    uploadHeader() {
      return { Authorization: getToken() };
    },
  },
  created() {},
  methods: {
    async changeSwitch(e) {
      if (e.str == "thirdOpen") {
        thirdOpen(e.e).then((ret) => {
          console.log("ret", ret);
        });
        return;
      }
      updatePush(e.e).then((ret) => {
        console.log("ret", ret);
      });
    },
    fetchData(listQuery, e) {
      this.listQuery = listQuery;
      console.log("fetchData", listQuery);
      const keyDefs = [
        { key: "stationName", matchType: "like" },
        { key: "stationStatus", matchType: "match" },
        { key: "thirdOpen", matchType: "match" },
        { key: "addrProvince", matchType: "like" },
        { key: "addrCity", matchType: "like" },
      ];
      if (e) {
        console.log(listQuery);
        listQuery.curPage = 1;
      }

      getStationList(mergeQuerrys(keyDefs, listQuery))
        .then((ret) => {
          console.log("ret", ret);
          this.listData = ret.data;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    itemNew() {
      console.log("itemNew");
      this.editType = "add";
      this.dialogTitle = "新建";
      this.editValues = {
        isMultiple: 0,
        stationCapacity: 0,
        combineProvinceAndCity: [],
        stationStatus: 1,
        addrProvince: "",
        addrCity: "",
        addrCounty: "",
        addrDesc: "",
        provinceCode: 0,
        cityCode: 0,
      };
      this.dialogVisible = true;
    },
    itemEdit({ type, item, items }) {
      console.log("itemEdit", type, item, items);
      item.isMultiple = item.isMultiple ? 1 : 0;
      if (item.sections) {
        item.sections.forEach((value, index) => {
          item[`sectionList${index}`] = value.sectionName;
        });
      }
      this.editType = "edit";
      const provinceAndCity = [item.provinceCode + "", item.cityCode + ""];
      // if (TextToCode[item.addrProvince] && TextToCode[item.addrProvince][item.addrCity]) {
      //   provinceAndCity = [TextToCode[item.addrProvince].code,
      //     TextToCode[item.addrProvince][item.addrCity].code]
      // }
      this.editValues = Object.assign(
        {
          combineProvinceAndCity: provinceAndCity,
          addrProvince: "",
          addrCity: "",
          addrCounty: "",
          provinceCode: 0,
          cityCode: 0,
          qqMap: {
            province: item.addrProvince,
            city: item.addrCity,
            address: item.addrDesc,
          },
        },
        item
      );
      console.log(998, this.editValues);
      this.dialogTitle = "修改";
      this.dialogVisible = true;
    },
    itemDelete({ type, item, items }) {
      console.log("itemDelete");
      if (type === "one") {
        delStation({ stationId: item.id }).then((ret) => {
          this.$message({
            type: "success",
            message: "删除成功！",
          });
          this.fetchData(this.listQuery);
        });
      } else if (type === "multi") {
        batchDel(delStation, items, {
          idname: "stationId",
          idvalue: "id",
        }).then((ret) => {
          this.$message({
            type: "success",
            message: "删除成功！",
          });
          this.fetchData(this.listQuery);
        });
      }
    },
    onSubmit(formData) {
      console.log("onSubmit", formData);
      // 格式化sections字段
      if (!formData.sections) formData.sections = [];
      for (let i = 0; i < formData.sectionCount; i++) {
        // 如果有sections的话
        if (formData.sections.length > i) {
          formData.sections[i].sectionName = formData[`sectionList${i}`];
        } else {
          // sections新增
          formData.sections.push({
            sectionName: formData[`sectionList${i}`],
          });
        }
      }

      // 补充省、区编号
      if (formData.combineProvinceAndCity.length > 1) {
        formData.provinceCode = formData.combineProvinceAndCity[0];
        formData.cityCode = formData.combineProvinceAndCity[1];
      }

      if (this.editType === "add") {
        // 新建
        addStation(formData).then((ret) => {
          console.log("add ret", ret);
          this.$message({
            type: "success",
            message: "添加成功！",
          });
          this.dialogVisible = false;
          this.fetchData(this.listQuery);
        });
      } else {
        // 修改
        putStation(formData).then((ret) => {
          console.log("edit ret", ret);
          this.$message({
            type: "success",
            message: "修改成功！",
          });
          this.dialogVisible = false;
          this.fetchData(this.listQuery);
        });
      }
    },
    addressChange(arr) {
      if (arr) {
        this.listQuery.addrProvince = CodeToText[arr[0]];
        this.listQuery.addrCity = CodeToText[arr[1]];
      } else {
        this.listQuery.addrProvince = "";
        this.listQuery.addrCity = "";
      }
    },
    exportExcelDia(listQuery) {
      const keyDefs = [
        { key: "stationName", matchType: "like" },
        { key: "stationStatus", matchType: "match" },
        { key: "thirdOpen", matchType: "match" },
        { key: "addrProvince", matchType: "like" },
        { key: "addrCity", matchType: "like" },
      ];
      exportStation(mergeQuerrys(keyDefs, listQuery))
        .then((ret) => {
          console.log("ret", ret);
          // this.listData = ret.data
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    downloadTemplate() {
      downloadTemplate().then((ret) => {
        console.log("ret", ret);
      });
    },
    importData() {
      this.dialogUploadVisible = true;
    },
    uploadDone() {
      this.dialogUploadVisible = false;
      this.fetchData(this.listQuery);
      console.log("uploadDone");
    },
    uploadError(err, file, fileList) {
      console.log(err);
      this.$message({
        type: "error",
        message: "导入出错！" + err,
      });
    },
    uploadSuccess(response, file, fileList) {
      this.$message({
        type: "success",
        message: "导入成功！",
      });
    },
  },
};
</script>
